package com.sz.mes.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.D;
import com.diboot.core.util.V;
import com.diboot.file.util.ExcelHelper;
import com.sz.mes.dto.RequestPurchaseDTO;
import com.sz.mes.entity.PurchaseOrder;
import com.sz.mes.entity.RequestPurchase;
import com.sz.mes.excel.model.RequestPurchaseExportModel;
import com.sz.mes.excel.model.SaleOrderExportModel;
import com.sz.mes.mapper.SaleOrderMapper;
import com.sz.mes.vo.PurchaseOrderListVO;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.SaleOrder;
import com.sz.mes.dto.SaleOrderDTO;
import com.sz.mes.vo.SaleOrderListVO;
import com.sz.mes.vo.SaleOrderDetailVO;
import com.sz.mes.service.SaleOrderService;
import com.sz.mes.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 销售订单 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-09-05
 * Copyright © szhs
 */
@RestController
@RequestMapping("/saleOrder")
@BindPermission(name = "销售订单")
@Slf4j
public class SaleOrderController extends BaseCustomCrudRestController<SaleOrder> {

    @Autowired
    private SaleOrderService saleOrderService;

    @Autowired
    private SaleOrderMapper saleOrderMapper;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    // @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(SaleOrderDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<SaleOrder> saleOrderQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getSpecification())) {
            saleOrderQueryWrapper.like("specification", queryDto.getSpecification());
        } else if (!StringUtils.isEmpty(queryDto.getProductName())) {
            saleOrderQueryWrapper.like("product_name", queryDto.getProductName());
        } else if (!StringUtils.isEmpty(queryDto.getProductNum())) {
            saleOrderQueryWrapper.like("product_num", queryDto.getProductNum());
        } else if (!StringUtils.isEmpty(queryDto.getOrderNum())) {
            saleOrderQueryWrapper.like("order_num", queryDto.getOrderNum());
        } else {
            return super.getViewObjectList(queryDto, pagination.setOrderBy("id:ASC"), SaleOrderListVO.class);
        }
        return super.getEntityListWithPaging(saleOrderQueryWrapper, pagination.setOrderBy("id:ASC"));
    }

    /**
     * 根据资源id查询ViewObject
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
        return super.getViewObject(id, SaleOrderDetailVO.class);
    }

    /**
     * 创建资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult createEntityMapping(@Valid @RequestBody SaleOrder entity) throws Exception {
        QueryWrapper<SaleOrder> saleOrderQueryWrapper = new QueryWrapper<>();
        saleOrderQueryWrapper.eq("order_num", entity.getOrderNum());
        saleOrderQueryWrapper.eq("order_row", entity.getOrderRow());
        SaleOrder saleOrder = saleOrderMapper.selectOne(saleOrderQueryWrapper);
        if (saleOrder == null) {
            return super.createEntity(entity);
        } else {
            return JsonResult.FAIL_OPERATION("该订单已存在");
        }
    }

    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    // @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody SaleOrder entity) throws Exception {
        try {
            QueryWrapper<SaleOrder> saleOrderQueryWrapper = new QueryWrapper<>();
            saleOrderQueryWrapper.eq("order_num", entity.getOrderNum());
            saleOrderQueryWrapper.eq("order_row", entity.getOrderRow());
            SaleOrder saleOrder = saleOrderMapper.selectOne(saleOrderQueryWrapper);
            SaleOrder currentSaleOrder = saleOrderMapper.selectById(id);
            if (entity.getOrderNum().equals(currentSaleOrder.getOrderNum()) && entity.getOrderRow().equals(currentSaleOrder.getOrderRow())) {
                // 如果什么都没改动，直接点击确定
                return super.updateEntity(id, entity);
            } else {
                // 如果改动了订单号或者订单行号，判断数据库是否存在
                if (saleOrder != null) {
                    return JsonResult.FAIL_EXCEPTION("该订单已存在");
                } else {
                    return super.updateEntity(id, entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.FAIL_EXCEPTION("请检查订单号及行号");
        }
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    // @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);
    }

    /**
     * excel导入
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/excel")
    public JsonResult insert(@Valid @RequestBody SaleOrder entity) throws Exception {
        List<String> orderNumAndRowList = new ArrayList<>();
        String excelData = entity.getExcelData();
        JSONArray objects = JSONObject.parseArray(excelData);
        for (Object object : objects) {
            HashMap<String, String> hashMap = JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class);
            String orderNum = hashMap.get("订单号");
            String orderRow = hashMap.get("订单行号");
            String orderNumAndRow = orderNum + "-" + orderRow;
            orderNumAndRowList.add(orderNumAndRow);
        }
        QueryWrapper<SaleOrder> saleOrderQueryWrapper = new QueryWrapper<>();
        for (String orderNumAndRow : orderNumAndRowList) {
            String[] orderNumAndRowArray = orderNumAndRow.split("-");
            saleOrderQueryWrapper.eq("order_num", orderNumAndRowArray[0]);
            saleOrderQueryWrapper.eq("order_row", orderNumAndRowArray[1]);
            try {
                SaleOrder saleOrder = saleOrderMapper.selectOne(saleOrderQueryWrapper);
                // 订单号，行号不存在的时候，才能新增
                if (saleOrder == null) {
                    return saleOrderService.insert(entity);
                } else {
                    return JsonResult.FAIL_EXCEPTION("该单号已存在,导入失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.FAIL_EXCEPTION("该单号已存在,导入失败");
            }
        }
        return JsonResult.OK("导入成功");
    }

    /**
     * 销售订单导出
     * @param requestPurchaseDTO
     * @return
     * @throws Exception
     */
    @Log(operation = "导出销售订单", businessObj = "SaleOrder")
    // @BindPermission(name = OperationCons.LABEL_EXPORT, code = OperationCons.CODE_EXPORT)
    @GetMapping("/export")
    public JsonResult export(SaleOrderDTO saleOrderDTO, @RequestParam(value = "columns", required = false) List<String> columns, HttpServletResponse response) throws Exception {
        QueryWrapper<SaleOrder> queryWrapper = super.buildQueryWrapperByQueryParams(saleOrderDTO);
        List<SaleOrder> saleOrderList = saleOrderService.getViewObjectList(queryWrapper, null, SaleOrder.class);
        if (V.isEmpty(saleOrderList)) {
            return new JsonResult(Status.FAIL_OPERATION, "销售订单列表为空，导出失败");
        }
        String fileName = "销售订单导出_" + D.today() + ".xlsx";
        List<SaleOrderExportModel> dataList = this.entityList2ExcelList(saleOrderList);
        ExcelHelper.exportExcel(response, fileName, SaleOrderExportModel.class, columns, dataList);
        return null;
    }

    /**
     * 实体列表转excel列表
     * @param saleOrderList
     * @return
     */
    private List<SaleOrderExportModel> entityList2ExcelList(List<SaleOrder> saleOrderList) {
        if (V.isEmpty(saleOrderList)) {
            return Collections.emptyList();
        }
        List<SaleOrderExportModel> excelModelList = new ArrayList<>();
        for (SaleOrder saleOrder : saleOrderList) {
            SaleOrderExportModel exportModel = new SaleOrderExportModel();
            BeanUtils.copyProperties(saleOrder, exportModel);
            excelModelList.add(exportModel);
        }
        return excelModelList;
    }
}
